package BackTracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Lettcode 90: https://leetcode-cn.com/problems/subsets-ii/
 */
public class subsetsWithDup {
    private int[] nums;

    private int length;

    public static void main(String[] args) {
        int[] nums = {1, 2 ,2};
        System.out.println(new subsetsWithDup().subsetsWithDup(nums));
    }

    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        this.nums = nums;
        this.length = nums.length;
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> curRes = new ArrayList<>();
        boolean[] visited = new boolean[length];
        for (int i = 0; i <= length; i++) {
            backTracking(res, curRes, i, visited, 0);
        }
        return res;
    }

    private void backTracking(List<List<Integer>> res, List<Integer> curRes, int subSetLength, boolean[] visited, int start) {
        if (subSetLength == 0) {
            res.add(new ArrayList<>(curRes));
            return;
        }
        for (int i = start; i < length; i++) {
//            很重要的剪枝条件
            if (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
                continue;
            }
            if (visited[i]) {
                continue;
            }
            curRes.add(nums[i]);
            visited[i] = true;
            backTracking(res, curRes, subSetLength - 1, visited, i + 1);
            curRes.remove(curRes.size() - 1);
            visited[i] = false;
        }
    }
}
